<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Vue全栈开发美团网,">










<meta name="description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第四章，主要内容为Mongoose和Redis基础知识视频地址：https://coding.imooc.com/class/280.html">
<meta name="keywords" content="Vue全栈开发美团网">
<meta property="og:type" content="article">
<meta property="og:title" content="【第四章】Vue全家桶+SSR+Koa2全栈开发美团网">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/09/12/full-stack-dev-meituan-with-vue-four/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第四章，主要内容为Mongoose和Redis基础知识视频地址：https://coding.imooc.com/class/280.html">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190912163052260.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190912163548486.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190912163713454.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916110341847.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190912165623135.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190912170213797.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916104632240.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916113945322.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916114851228.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916115342458.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916171450395.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916171924908.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916172857477.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916173308537.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916173712835.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916174738279.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916103313149.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916104532405.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916104632240.jpg">
<meta property="og:updated_time" content="2019-09-24T00:58:49.150Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第四章】Vue全家桶+SSR+Koa2全栈开发美团网">
<meta name="twitter:description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第四章，主要内容为Mongoose和Redis基础知识视频地址：https://coding.imooc.com/class/280.html">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190912163052260.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/09/12/full-stack-dev-meituan-with-vue-four/">





  <title>【第四章】Vue全家桶+SSR+Koa2全栈开发美团网 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/09/12/full-stack-dev-meituan-with-vue-four/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第四章】Vue全家桶+SSR+Koa2全栈开发美团网</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-12T16:01:33+08:00">
                2019-09-12
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Vue/" itemprop="url" rel="index">
                    <span itemprop="name">Vue</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第四章，主要内容为Mongoose和Redis基础知识<br>视频地址：<a href="https://coding.imooc.com/class/280.html" target="_blank" rel="noopener">https://coding.imooc.com/class/280.html</a></p>
<a id="more"></a>
<h1 id="Mongoose基础"><a href="#Mongoose基础" class="headerlink" title="Mongoose基础"></a>Mongoose基础</h1><h2 id="MongoDB概念与安装"><a href="#MongoDB概念与安装" class="headerlink" title="MongoDB概念与安装"></a>MongoDB概念与安装</h2><p>详见 《【第十二章】一步一步学习SpringBoot2——Springboot集成MongoDB》</p>
<ol>
<li><p>mysql与mongdb概念区别<br><img src="/blog/images/20190912163052260.jpg" alt="mysql与mongdb概念区别"></p>
</li>
<li><p>启动MongDB服务<br><img src="/blog/images/20190912163548486.jpg" alt="启动MongDB服务"></p>
</li>
<li><p>MongoDB可视化工具RoBo 3T<br><img src="/blog/images/20190912163713454.jpg" alt="RoBo 3T"></p>
</li>
</ol>
<h2 id="Mongoose的作用"><a href="#Mongoose的作用" class="headerlink" title="Mongoose的作用"></a>Mongoose的作用</h2><blockquote>
<p>Mongoose操作MongDB数据库非常非常简单</p>
</blockquote>
<p>本节部分内容引用自：<a href="https://blog.csdn.net/thatway_wp/article/details/79388522" target="_blank" rel="noopener">https://blog.csdn.net/thatway_wp/article/details/79388522</a></p>
<p>Mongoose中文文档：<a href="https://xiaoxiami.gitbook.io/mongoose/" target="_blank" rel="noopener">https://xiaoxiami.gitbook.io/mongoose/</a></p>
<p>Mongoose中三个主要概念：<strong><em>模式schemas、模型models、实例</em></strong><br><img src="/blog/images/20190916110341847.jpg" alt="Mongoose中三个主要概念"></p>
<p><strong>Schema生成Model，Model实例化成为Document。</strong></p>
<blockquote>
<p>i. 模式schemas： Schema用于定义数据表的结构(字段、类型等)。类似创建表时的数据定义(不仅仅可以定义文档的结构和属性，还可以定义文档的实例方法、静态模型方法、复合索引等)，每个Schema会映射到mongodb中的一个collection，Schema不具备操作数据库的能力。<br>ii. 模型models：由Schema编译而成的构造器，具有抽象属性和行为(可以理解为一个类)，定义了对数据库进行增删查改的方法。<br>Model的每一个实例（instance）就是一个文档document。<br>iii. 实例： Document是new Model后创建的实例，通过实例具体调用操作”数据表”的方法，它的操作会影响数据库。</p>
</blockquote>
<h2 id="Mongoose的使用"><a href="#Mongoose的使用" class="headerlink" title="Mongoose的使用"></a>Mongoose的使用</h2><h3 id="Mongoose的配置与连接"><a href="#Mongoose的配置与连接" class="headerlink" title="Mongoose的配置与连接"></a>Mongoose的配置与连接</h3><ol>
<li>安装Mongoose<figure class="highlight 1c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//进入项目目录</span></span><br><span class="line">npm install mongoose</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190912165623135.jpg" alt="安装Mongoose"></p>
<ol start="2">
<li><p>声明MongoDB的配置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//dbs/config.js</span></span><br><span class="line"><span class="keyword">module</span>.<span class="keyword">exports</span> = (&#123;</span><br><span class="line">	<span class="string">'dbs'</span>: <span class="string">'mongodb://127.0.0.1:27017/dbs'</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p>连接MongDB数据库</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//app.js</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">'mongoose'</span>)</span><br><span class="line"><span class="keyword">const</span> dbConfig = <span class="built_in">require</span>(<span class="string">'./dbs/config'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//connect mongoDB</span></span><br><span class="line">mongoose.connect(dbConfig.dbs,&#123;</span><br><span class="line">	useNewUrlParser: <span class="literal">true</span>,</span><br><span class="line">	useUnifiedTopology: <span class="literal">true</span> </span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">mongoose.connection.on(<span class="string">'connected'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Connection success!'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190912170213797.jpg" alt="连接MongDB数据库"></p>
<ol start="4">
<li>定义Schema——对应数据表<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//person.js</span></span><br><span class="line"><span class="comment">//定义schema -- 相当于建表</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">'mongoose'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> personSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">	name: <span class="built_in">String</span>,</span><br><span class="line">	age: <span class="built_in">Number</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义model来关联Schema和实例，用于操作数据表，并导出。</span></span><br><span class="line"><span class="comment">//对exports的理解，exports.xx代表的是 当我require后赋给一个var后，</span></span><br><span class="line"><span class="comment">//可以用var_name.xx的形式去调用它.</span></span><br><span class="line"><span class="built_in">module</span>.exports =  mongoose.model(<span class="string">'Person'</span>,personSchema)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="通过mongoose对数据进行新增操作"><a href="#通过mongoose对数据进行新增操作" class="headerlink" title="通过mongoose对数据进行新增操作"></a>通过mongoose对数据进行新增操作</h3><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//users.js</span></span><br><span class="line"><span class="comment">//引入模型</span></span><br><span class="line">const Person = require(<span class="string">'../dbs/models/person'</span>)</span><br><span class="line"></span><br><span class="line">router.post(<span class="string">'/addPerson'</span>, async function(ctx)&#123;</span><br><span class="line">	<span class="comment">//创建实例</span></span><br><span class="line">	<span class="comment">//console.log(ctx.request)</span></span><br><span class="line">	const person = new Person(&#123;</span><br><span class="line">		name: ctx<span class="selector-class">.request</span><span class="selector-class">.body</span><span class="selector-class">.name</span>,</span><br><span class="line">		age: ctx<span class="selector-class">.request</span><span class="selector-class">.body</span><span class="selector-class">.age</span></span><br><span class="line">	&#125;,false)</span><br><span class="line">	let code</span><br><span class="line">	try&#123;</span><br><span class="line">		<span class="comment">//保存数据</span></span><br><span class="line">		await person.save()</span><br><span class="line">		<span class="selector-tag">code</span> = <span class="number">0</span></span><br><span class="line">	&#125;catch(e)&#123;</span><br><span class="line">		<span class="selector-tag">code</span> = -<span class="number">1</span></span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	ctx<span class="selector-class">.body</span> = &#123;</span><br><span class="line">		<span class="selector-tag">code</span>: code</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>数据保存成功如下图所示：<br><img src="/blog/images/20190916104632240.jpg" alt="数据保存成功"></p>
<h3 id="通过mongoose对数据进行查询操作"><a href="#通过mongoose对数据进行查询操作" class="headerlink" title="通过mongoose对数据进行查询操作"></a>通过mongoose对数据进行查询操作</h3><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">router.post(<span class="string">'/getPerson'</span>, async function(ctx)&#123;</span><br><span class="line">	<span class="comment">//使用模型来查询数据————类似于操作类的静态方法</span></span><br><span class="line">	const result = await Person.findOne(&#123;name:ctx<span class="selector-class">.request</span><span class="selector-class">.body</span><span class="selector-class">.name</span>&#125;)</span><br><span class="line">	const results = await Person.find(&#123;name:ctx<span class="selector-class">.request</span><span class="selector-class">.body</span><span class="selector-class">.name</span>&#125;)</span><br><span class="line">	</span><br><span class="line">	ctx<span class="selector-class">.body</span> = &#123;</span><br><span class="line">		<span class="selector-tag">code</span>: <span class="number">0</span>,</span><br><span class="line">		result:result,</span><br><span class="line">		results:results</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>数据查询成功如下图所示：<br><img src="/blog/images/20190916113945322.jpg" alt="数据查询成功"></p>
<h3 id="通过mongoose对数据进行更新操作"><a href="#通过mongoose对数据进行更新操作" class="headerlink" title="通过mongoose对数据进行更新操作"></a>通过mongoose对数据进行更新操作</h3><figure class="highlight roboconf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">router.post('/updatePerson', async function(ctx)&#123;</span><br><span class="line">	//使用模型来更新数据————先查询在更新</span><br><span class="line">	<span class="attribute">const result = await Person.where(&#123;</span></span><br><span class="line"><span class="attribute">		name</span>: ctx<span class="variable">.request</span><span class="variable">.body</span><span class="variable">.name</span></span><br><span class="line">	&#125;)<span class="variable">.update</span>(&#123;</span><br><span class="line">		age: ctx<span class="variable">.request</span><span class="variable">.body</span><span class="variable">.age</span></span><br><span class="line">	&#125;);</span><br><span class="line">	</span><br><span class="line">	<span class="attribute">ctx.body = &#123;</span></span><br><span class="line"><span class="attribute">		code</span>: 0,</span><br><span class="line">		result:result,</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>数据更新成功如下图所示：<br><img src="/blog/images/20190916114851228.jpg" alt="数据更新成功"></p>
<h3 id="通过mongoose对数据进行查询删除操作-开发过程中禁止删除"><a href="#通过mongoose对数据进行查询删除操作-开发过程中禁止删除" class="headerlink" title="通过mongoose对数据进行查询删除操作(开发过程中禁止删除)"></a>通过mongoose对数据进行查询删除操作(开发过程中禁止删除)</h3><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">router.post(<span class="string">'/removePerson'</span>, <span class="function"><span class="keyword">async</span> <span class="title">function</span>(<span class="params">ctx</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//使用模型来删除数据————先查询再删除</span></span><br><span class="line">	<span class="keyword">const</span> result = <span class="keyword">await</span> Person.<span class="keyword">where</span>(&#123;</span><br><span class="line">		name: ctx.request.body.name</span><br><span class="line">	&#125;).<span class="keyword">remove</span>();</span><br><span class="line">	</span><br><span class="line">	ctx.body = &#123;</span><br><span class="line">		code: <span class="number">0</span>,</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>数据删除成功如下图所示：<br><img src="/blog/images/20190916115342458.jpg" alt="数据删除成功"></p>
<h1 id="Redis基础"><a href="#Redis基础" class="headerlink" title="Redis基础"></a>Redis基础</h1><h2 id="Redis的概念与安装"><a href="#Redis的概念与安装" class="headerlink" title="Redis的概念与安装"></a>Redis的概念与安装</h2><p>见《【第七章】一步一步学习SpringBoot2——集成Redis缓存》</p>
<p>启动Redis服务：<br><img src="/blog/images/20190916171450395.jpg" alt="启动Redis服务"></p>
<h2 id="Redis的应用场景"><a href="#Redis的应用场景" class="headerlink" title="Redis的应用场景"></a>Redis的应用场景</h2><blockquote>
<p>在服务端的redis中保存用户的session</p>
</blockquote>
<h2 id="Redis的用法"><a href="#Redis的用法" class="headerlink" title="Redis的用法"></a>Redis的用法</h2><ol>
<li>安装Redis相关的中间件<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//koa-generic-session 处理koa与session的，主要操作session</span></span><br><span class="line"><span class="comment">//koa-redis 处理redis。这两个中间件常搭配一起使用</span></span><br><span class="line">npm intall koa-<span class="keyword">generic</span>-session koa-redis</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190916171924908.jpg" alt="安装Redis相关的中间件"></p>
<ol start="2">
<li>Redis存储Session代码示例<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//app.js</span></span><br><span class="line"><span class="keyword">const</span> session = <span class="keyword">require</span>(<span class="string">'koa-generic-session'</span>)</span><br><span class="line"><span class="keyword">const</span> Redis = <span class="keyword">require</span>(<span class="string">'koa-redis'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//定义Session加密字符串</span></span><br><span class="line">app.keys = [<span class="string">'keys'</span>,<span class="string">'keyskeysdar34sdf'</span>]</span><br><span class="line"><span class="comment">//使用session中间件，并设置用redis保存session，默认使用内存存储</span></span><br><span class="line"><span class="comment">//使用如下语句Redis已经连接成功</span></span><br><span class="line">app.<span class="keyword">use</span>(session(&#123;</span><br><span class="line">	key: <span class="string">'mt'</span>, <span class="comment">//cookie的key的前缀</span></span><br><span class="line">	prefix: <span class="string">'mtpr'</span>, <span class="comment">//redis的key的前缀</span></span><br><span class="line">	Store: <span class="keyword">new</span> Redis()</span><br><span class="line">&#125;))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//middleware/koa-pv.js</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pv</span><span class="params">(ctx)</span></span>&#123;</span><br><span class="line">	<span class="comment">//ctx是应用中的全局对象：挂载所有的Request和Response，被各个中间件所引用</span></span><br><span class="line">	ctx.session.count++</span><br><span class="line">	<span class="keyword">global</span>.console.log(<span class="string">'pv'</span>,ctx.path)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190916172857477.jpg" alt="Redis存储Session代码示例"><br><img src="/blog/images/20190916173308537.jpg" alt="Redis存储Session代码示例"></p>
<ol start="3">
<li>在Redis中查看数据<br><img src="/blog/images/20190916173712835.jpg" alt="在Redis中查看数据"></li>
</ol>
<h2 id="直接操作Redis"><a href="#直接操作Redis" class="headerlink" title="直接操作Redis"></a>直接操作Redis</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//user.js</span></span><br><span class="line"><span class="keyword">const</span> Redis = <span class="built_in">require</span>(<span class="string">'koa-redis'</span>)</span><br><span class="line"><span class="comment">//创建Redis客户端</span></span><br><span class="line"><span class="keyword">const</span> Store = <span class="keyword">new</span> Redis().client</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//操作Redis</span></span><br><span class="line">router.get(<span class="string">'/optRedis'</span>,<span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params">ctx</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> st = <span class="keyword">await</span> Store.hset(<span class="string">'fix'</span>,<span class="string">'name'</span>,<span class="built_in">Math</span>.random())</span><br><span class="line">  ctx.body = &#123;</span><br><span class="line">	  code:<span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190916174738279.jpg" alt="直接操作Redis"></p>
<h1 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h1><h2 id="mongoose无法使用save存数据"><a href="#mongoose无法使用save存数据" class="headerlink" title="mongoose无法使用save存数据"></a>mongoose无法使用save存数据</h2><p>错误描述：使用mongoose的save()，无法保存数据到MongoDB中</p>
<p>错误原因：koa2的post请求ctx.request.body为空<br><img src="/blog/images/20190916103313149.jpg" alt="koa2的post请求ctx.request.body为空"></p>
<p>解决办法： 改为使用如下的方式提交数据<br><img src="/blog/images/20190916104532405.jpg" alt="使用如下的方式提交"><br><img src="/blog/images/20190916104632240.jpg" alt="使用如下的方式提交"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Vue全栈开发美团网/" rel="tag"># Vue全栈开发美团网</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/09/09/full-stack-dev-meituan-with-vue-three/" rel="next" title="【第三章】Vue全家桶+SSR+Koa2全栈开发美团网">
                <i class="fa fa-chevron-left"></i> 【第三章】Vue全家桶+SSR+Koa2全栈开发美团网
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/09/16/full-stack-dev-meituan-with-vue-five/" rel="prev" title="【第五章】Vue全家桶+SSR+Koa2全栈开发美团网">
                【第五章】Vue全家桶+SSR+Koa2全栈开发美团网 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Mongoose基础"><span class="nav-number">1.</span> <span class="nav-text">Mongoose基础</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB概念与安装"><span class="nav-number">1.1.</span> <span class="nav-text">MongoDB概念与安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mongoose的作用"><span class="nav-number">1.2.</span> <span class="nav-text">Mongoose的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mongoose的使用"><span class="nav-number">1.3.</span> <span class="nav-text">Mongoose的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Mongoose的配置与连接"><span class="nav-number">1.3.1.</span> <span class="nav-text">Mongoose的配置与连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过mongoose对数据进行新增操作"><span class="nav-number">1.3.2.</span> <span class="nav-text">通过mongoose对数据进行新增操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过mongoose对数据进行查询操作"><span class="nav-number">1.3.3.</span> <span class="nav-text">通过mongoose对数据进行查询操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过mongoose对数据进行更新操作"><span class="nav-number">1.3.4.</span> <span class="nav-text">通过mongoose对数据进行更新操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过mongoose对数据进行查询删除操作-开发过程中禁止删除"><span class="nav-number">1.3.5.</span> <span class="nav-text">通过mongoose对数据进行查询删除操作(开发过程中禁止删除)</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis基础"><span class="nav-number">2.</span> <span class="nav-text">Redis基础</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis的概念与安装"><span class="nav-number">2.1.</span> <span class="nav-text">Redis的概念与安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis的应用场景"><span class="nav-number">2.2.</span> <span class="nav-text">Redis的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis的用法"><span class="nav-number">2.3.</span> <span class="nav-text">Redis的用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#直接操作Redis"><span class="nav-number">2.4.</span> <span class="nav-text">直接操作Redis</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常见错误"><span class="nav-number">3.</span> <span class="nav-text">常见错误</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#mongoose无法使用save存数据"><span class="nav-number">3.1.</span> <span class="nav-text">mongoose无法使用save存数据</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
